import Vue from 'vue'

/**
 * 保存定时器
 */
let taskTimers = []

/**
 * 任务提醒 store
 */
const moduleParamet = {
  /**
   * 格式：{table_name.col_name: {
   *   col_value: value_desc
   * }}
   */
  state: {
    /**
     * 任务模板,格式:{title, cycleType 周期: day|week, weekDay 每个周期的第n天, time 时间格式: mm:ss}
     */
    taskTemplates: [],
    /**
     * 当天任务,格式:{title, time, isFinish}
     */
    tasks: [],
    /**
     * 任务日期,判断任务是否过期
     */
    taskDate: '',
    /**
     * 是否第一次运行
     */
    isFirstRun: true
  },
  getters: {
    getTaskTemplates (state) {
      return state.taskTemplates
    },
    getTasks (state) {
      return state.tasks
    },
    isFirstRun (state) {
      return state.isFirstRun
    }
  },
  mutations: {
    addTaskTemplate (state, { template }) {
      state.taskTemplates.push(template)
    },
    mergeTaskTemplate (state, { index, template }) {
      // Object.assign(state.taskTemplates[index], template)
      state.taskTemplates[index] = Object.assign({}, state.taskTemplates[index], template)
    },
    removeTaskTemplate (state, { title }) {
      for (let i=0;i<state.taskTemplates.length;i++) {
        if (state.taskTemplates[i].title === title) {
          state.taskTemplates.splice(i, 1)
          break
        }
      }
    },
    addTask (state, { task }) {
      state.tasks.push(task)
    },
    removeTask (state, { index }) {
      state.tasks.splice(index, 1)
    },
    finishTask (state, { index }) {
      state.tasks[index].isFinish = true
    },
    resetTaskTemplates (state) {
      Vue.set(state, 'taskTemplates', [])
      Vue.set(state, 'tasks', [])
      state.isFirstRun = true;
    },
    resetTask (state) {
      Vue.set(state, 'tasks', [])
    },
    setTaskDate (state, { day }) {
      state.taskDate = day
    },
    setFinishRun (state, { value }) {
      state.isFirstRun = value
    },
    saveAllTask (state) {
      localStorage.__task = JSON.stringify(state)
    },
    loadAllTask (state) {
      if (localStorage.__task && localStorage.__task !== 'undefined') {
        let task = JSON.parse(localStorage.__task)
        Object.assign(state, task)
      }
    }
  },
  actions: {
    /**
     * 初次运行,加载初始化数据
     */
    firstRun ({ commit }){

      commit({ type: 'resetTaskTemplates' })

      let orderTemplate = {
        title: '工作日点餐',
        cycleType: 'day',
        time: '15:00'
      }
      let workingHours = {
        title: '填报工时',
        cycleType: 'day',
        time: '17:20'
      }
      let dayWiki = {
        title: '更新日报',
        cycleType: 'day',
        time: '17:00'
      }
      let weekWiki = {
        title: '更新周报',
        cycleType: 'week',
        weekDay: 5,
        time: '11:00'
      }

      commit({ type: 'addTaskTemplate', template: orderTemplate})
      commit({ type: 'addTaskTemplate', template: workingHours})
      commit({ type: 'addTaskTemplate', template: dayWiki})
      commit({ type: 'addTaskTemplate', template: weekWiki})

      commit({ type: 'setFinishRun', value: false })
      commit({ type: 'saveAllTask' })
    },

    /**
     * 创建今天的任务
     */
    createTodayTask ({ commit, state }) {

      let now = new Date()
      let today = now.format('yyyy-MM-dd')
      let weekDay = now.getDay()

      if (state.taskDate !== today) {
        commit({ type: 'resetTask' })

        state.taskTemplates
          .filter(x => x.cycleType === 'day' || (x.cycleType === 'week' && x.weekDay === weekDay))
          .map(x => {
            return {title: x.title, time: x.time, isFinish: false}
          })
          .forEach(x => commit({ type: 'addTask', task: x}))

        commit({ type: 'setTaskDate', day: today })
        commit({ type: 'saveAllTask' })
      }
    },
    /**
     * 刷新提醒定时器
     */
    flushTimer : ({ state, rootGetters }) => {    // 开发环境为浏览器页面
      console.log('is dev : ' + rootGetters.isDev)
      //开发环境与生产环境执行不同
      if (rootGetters.isDev){
        //取消已有定时器
        taskTimers.forEach(clearTimeout)

        let now = new Date()
        let today = now.format('yyyy-MM-dd')
        let timestamp = now.getTime()

        let unFinishTasks = state.tasks
          .filter(task => task && !task.isFinish)
          .map(task => {
            return { timeout: new Date(`${today} ${task.time}`).getTime() - timestamp, ... task}
          })

        taskTimers = unFinishTasks.filter(task => task.timeout > 0)
          .map(task => {
            return setTimeout((t) => {
              if (window.Notification) {
                Notification.requestPermission(function (perm) {
                  if (perm == "granted") {
                    let notification = new Notification('浪潮小助手提醒', {
                        dir: 'auto',
                        lang: 'hi',
                        tag: t.title + new Date().getTime(),
                        icon: '/favicon.ico',
                        body:  `${t.time} 该${t.title}了`,
                        requireInteraction: true
                    });
                  } else {
                    alert('浪潮小助手提醒:\n' + t.title)
                  }
                })
              } else {
                alert('浪潮小助手提醒:\n' + t.title)
              }

              console.log('已超时的未完成任务减少1')
            }, task.timeout, task)
          })

        console.log('创建定时器:', taskTimers)
        console.log('已超时的未完成任务:' + unFinishTasks.filter(x => x.timeout <= 0).length)
      } else {
        chrome.extension.sendMessage({ type: 'flushTask' })
      }
    }
  }
}

export default moduleParamet